import torch
import logging

import matplotlib.pyplot as plt
import numpy as np

from trl import SFTTrainer
from transformers import TrainingArguments
from datasets import load_dataset
from prompt_setting import alpaca_prompt
from unsloth import FastLanguageModel

# 定义日志输出格式
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='logs/training.log', level=logging.INFO, format=LOG_FORMAT)


class llamaNN():

    def __init__(self):
        self.max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
        self.dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
        self.load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
        model, self.tokenizer = FastLanguageModel.from_pretrained(
            #model_name = "unsloth/llama-3-8b-bnb-4bit",
            model_name="./models/llama-3-8b-bnb-4bit",
            max_seq_length = self.max_seq_length,
            dtype = self.dtype,
            load_in_4bit = self.load_in_4bit,
            # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
        )


        self.model = FastLanguageModel.get_peft_model(
            model,
            r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
            target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                              "gate_proj", "up_proj", "down_proj",],
            lora_alpha = 16,
            lora_dropout = 0, # Supports any, but = 0 is optimized
            bias = "none",    # Supports any, but = "none" is optimized
            # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
            use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
            random_state = 3407,
            use_rslora = False,  # We support rank stabilized LoRA
            loftq_config = None, # And LoftQ
        )

        self.EOS_TOKEN = self.tokenizer.eos_token # Must add EOS_TOKEN



    def get_dataset(self):
        EOS_TOKEN = self.EOS_TOKEN
        def formatting_prompts_func(examples):
            instructions = examples["instruction"]
            inputs = examples["input"]
            outputs = examples["output"]
            texts = []
            for instruction, input, output in zip(instructions, inputs, outputs):
                # Must add EOS_TOKEN, otherwise your generation will go on forever!
                text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
                texts.append(text)
            return {"text": texts, }

        dataset = load_dataset("traning_datasets", split="train")
        dataset = dataset.map(formatting_prompts_func, batched=True, )
        return dataset

    def init_trainer(self):

        trainer = SFTTrainer(
            model=self.model,
            tokenizer=self.tokenizer,
            train_dataset=self.get_dataset(), # 训练集
            # eval_dataset=val_dataset,  # 验证集
            dataset_text_field="text",
            max_seq_length=self.max_seq_length,
            dataset_num_proc=2,
            packing=False,  # Can make training 5x faster for short sequences.
            args=TrainingArguments(
                per_device_train_batch_size=2, #这表示在每个训练步骤中，每个设备（例如 GPU）处理的训练示例数量。这里设置为 2，即每台设备在每一步中处理 2 个示例
                gradient_accumulation_steps=4,  # 梯度累积步数）：定义执行参数更新前的梯度累积步数。通过在多个步骤中累积梯度，可以有效增加批次大小。此处设置为 4，表示在更新模型参数之前，梯度将累积 4 个步骤。
                warmup_steps=10, # 设置训练过程中的练习步数，将学习率从 0 逐步提高到所提供的值。这里设置为 5，因此学习率将在前 5 步中线性增加。
                max_steps=60, # 这定义了要执行的训练步骤总数。这里设置为 50，意味着训练将在 50 步后停止。
                learning_rate=2e-4, # 这表示用于训练的第一个学习率。这里设置为 2e-4（2 乘以 10 的-4 次方）。
                fp16=not torch.cuda.is_bf16_supported(), # 是否使用混合精度训练（FP16）。如果GPU支持bfloat16（BF16），则使用BF16，否则使用FP16。FP16可以减少内存使用并加快训练速度，但可能需要额外的稳定性技巧。
                bf16=torch.cuda.is_bf16_supported(), # 是否使用bfloat16精度进行训练。如果GPU支持BF16，这将被设置为True。BF16提供与FP16相似的好处，但有时更稳定。
                optim="adamw_8bit", # 优化器类型。这里指定使用AdamW优化器，并应用8-bit量化以减少内存使用。
                weight_decay=0.01, # 权重衰减。这是一种正则化技术，用于防止过拟合，通过在损失函数中添加一个与权重大小成比例的惩罚项。
                lr_scheduler_type="linear", # 学习率调度器类型。这里指定使用线性衰减的学习率调度器。
                seed=3407, # 随机种子。用于确保实验的可重复性。
                output_dir="outputs", # 模型预测和检查点输出的目录
                save_strategy="steps", # 保存模型的步数间隔，如果save_strategy =“steps”，则两个检查点保存之前的更新步骤数。 应该是整数 或 范围“[0,1)”内的浮点数。 如果小于 1，将被解释为总训练步数的比率。
                save_steps=0.5, # 保存模型的步数间隔，如果save_strategy =“steps”，则两个检查点保存之前的更新步骤数。 应该是整数 或 范围“[0,1)”内的浮点数。 如果小于 1，将被解释为总训练步数的比率。
                num_train_epochs=20, # 训练的轮数（epochs）。
                log_level= "info", # 设置主进程上使用的日志级别
                logging_strategy="steps", # 训练过程中，checkpoint的保存策略
                logging_steps=1, # 设置记录训练指标和损失的时间间隔。我们将其设置为 1，因此每训练一步后都会打印日志。
                logging_first_step=True,
            ),
        )

        gpu_stats = torch.cuda.get_device_properties(0)
        start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
        max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
        logging.info(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
        logging.info(f"{start_gpu_memory} GB of memory reserved.")

        trainer_stats = trainer.train()

        for obj in trainer.state.log_history:
            logging.info(str(obj))

        # self.train_losses = trainer.state.log_history
        self.curve(trainer.state.log_history)

        used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
        used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
        used_percentage = round(used_memory / max_memory * 100, 3)
        lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
        logging.info(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
        logging.info(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
        logging.info(f"Peak reserved memory = {used_memory} GB.")
        logging.info(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
        logging.info(f"Peak reserved memory % of max memory = {used_percentage} %.")
        logging.info(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")


        self.tokenizer.save_pretrained("./lora_model")
        logging.info("save pretrained model")
        self.model.save_pretrained("./lora_model")  # Local saving
        logging.info("save lora model")
        #self.tokenizer.save_pretrained("lm3_lora_model")
        # model.push_to_hub("your_name/lora_model", token = "...") # Online saving
        # tokenizer.push_to_hub("your_name/lora_model", token = "...") # Online saving

        # 保存模型为gguf
        self.model.save_pretrained_gguf("gguf_model",  self.tokenizer, quantization_method = "q4_k_m")



    def inference(self):

        model, tokenizer = FastLanguageModel.from_pretrained(
            model_name="lora_model",  # YOUR MODEL YOU USED FOR TRAINING
            max_seq_length=self.max_seq_length,
            dtype=self.dtype,
            load_in_4bit=self.load_in_4bit,
        )
        FastLanguageModel.for_inference(model)  # Enable native 2x faster inference

        inputs = tokenizer(
            [
                alpaca_prompt.format(
                    "技术开发的使命是什么",  # instruction
                    "",  # input
                    "",  # output - leave this blank for generation!
                )
            ], return_tensors="pt").to("cuda")

        outputs = model.generate(**inputs, max_new_tokens=128, use_cache=True)
        print(tokenizer.batch_decode(outputs))
        # from transformers import TextStreamer
        # text_streamer = TextStreamer(tokenizer)
        # _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128)

    
    def curve(self,log_history):
        # 确保 data 被正确填充
        if not log_history:
            logging.warning("No training losses to plot.")
            return

       # 过滤掉那些不包含 'loss' 和 'learning_rate' 的条目
        filtered_log_history = [entry for entry in log_history if 'loss' in entry]

        # 确保 filtered_log_history 被正确填充
        if not filtered_log_history:
            logging.warning("No training losses to plot with consistent keys.")
            return

        # 提取数据用于绘图
        steps = [d['step'] for d in filtered_log_history]
        losses = [d.get('loss', 0) for d in filtered_log_history]  # 使用 get 方法提供默认值
        grad_norms = [d.get('grad_norm', 0) for d in filtered_log_history]  # 使用 get 方法提供默认值
        learning_rates = [d.get('learning_rate', 0) for d in filtered_log_history]  # 使用 get 方法提供默认值
        epochs = [d.get('epoch', 0) for d in filtered_log_history]  # 使用 get 方法提供默认值
        smooth_losses = [np.mean(losses[max(i-1, 0): min(i+2, len(losses))]) for i in range(len(losses))] # 计算平滑后的损失值


        # 创建图表
        plt.figure(figsize=(14, 7))

        # 绘制损失曲线
        plt.subplot(2, 2, 1)
        # 绘制原始损失数据
        plt.plot(steps, losses, label='Original Loss', marker='o', color='orange', linestyle='--', linewidth=1)
        # 绘制平滑后的损失数据
        plt.plot(steps, smooth_losses, label='Smooth Loss', color='blue', linewidth=1)
        plt.title('Loss per Step')
        plt.xlabel('Step')
        plt.ylabel('Loss')
        plt.legend()

        # 绘制梯度范数曲线
        plt.subplot(2, 2, 2)
        plt.plot(steps, grad_norms, label='Gradient Norm', color='orange')
        plt.title('Gradient Norm per Step')
        plt.xlabel('Step')
        plt.ylabel('Gradient Norm')
        plt.legend()

        # 绘制学习率曲线
        plt.subplot(2, 2, 3)
        plt.plot(steps, learning_rates, label='Learning Rate', color='green')
        plt.title('Learning Rate per Step')
        plt.xlabel('Step')
        plt.ylabel('Learning Rate')
        plt.legend()

        # 绘制周期曲线
        plt.subplot(2, 2, 4)
        plt.plot(steps, epochs, label='Epoch', color='red')
        plt.title('Epoch per Step')
        plt.xlabel('Step')
        plt.ylabel('Epoch')
        plt.legend()

        # 调整子图间距
        plt.tight_layout()

        # 保存图像
        plt.savefig('logs/training_analysis.png', dpi=300, bbox_inches='tight')

        # 显示图表
        plt.close()